package cn.usian.filter;

import cn.usian.common.R;
import com.alibaba.fastjson.JSON;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns ="/*")
public class LoginCheckFilter implements Filter {
    //该类专门用来匹配请求路径的
    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.由于request对象需要使用子类特有的方法，所以强制类型转换
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //2.获取本次请求的url
        String requestURI = request.getRequestURI();
        //3.定义一个数组存储需要放行的url,判定本次请求是否需要登录权限
        String []urls={"/backend/**","/front/**","/employee/login"};
        boolean flag=checkurl(urls,requestURI);
        if(flag){
            filterChain.doFilter(request,response);
            return;
        }
         //如果需要登录权限的，从session中取出登录成功的标记检查
        HttpSession session = request.getSession();
        if(session.getAttribute("employee")!=null){
            //如果用户已经登录，也可以直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //如果没有登录，返回数据前端，让前端跳转
        /*
         因为目前使用的Filter，不是springmvc，所以如果需要返回json数据，需要自己转换
        */
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);

    }
    //检查本次请求路径是否属于直接放行的资源
    private  boolean checkurl(String []urls,String requestURI){
        //遍历所有放行的路径,是否与本次的请求路径匹配
        for(String url:urls){
            if(antPathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
